package com.googlecode.yoohoo.io.socket.stream;

import java.util.HashMap;
import java.util.Map;

import com.googlecode.yoohoo.xmppcore.protocol.IFeature;
import com.googlecode.yoohoo.xmppcore.stream.features.Features;

public class StreamFeaturesManager implements IStreamFeaturesManager {
	private Map<NegotiationPhase, Features> featuresMap;
	private Map<NegotiationPhase, String> advertisementMap;
	
	public StreamFeaturesManager() {
		featuresMap = new HashMap<NegotiationPhase, Features>();
		advertisementMap = new HashMap<NegotiationPhase, String>();
	}
	
	@Override
	public synchronized void addFeature(IFeature feature, NegotiationPhase phase) {
		Features features = featuresMap.get(phase);
		if (features == null) {
			features = new Features();
			featuresMap.put(phase, features);
		}
		
		features.getFeatures().add(feature);
		String advertisement = features.toXml();
		advertisementMap.put(phase, advertisement);
		updateAdvertisement(phase);
	}

	@Override
	public String getFeaturesAdvertisement(NegotiationPhase phase) {
		String advertisement = advertisementMap.get(phase);
		if (advertisement == null)
			return "<stream:features/>";

		return advertisement;
	}

	@Override
	public synchronized void removeFeature(IFeature feature, NegotiationPhase phase) {
		Features features = featuresMap.get(phase);
		if (features == null) {
			return;
		}
		
		features.getFeatures().remove(feature);
		updateAdvertisement(phase);
	}

	private void updateAdvertisement(NegotiationPhase phase) {
		Features features = featuresMap.get(phase);
		if (features == null)
			return;
		
		advertisementMap.put(phase, features.toXml());
	}

}
